package minimips.isa;

import minimips.computer.Computer;
import minimips.exception.MemoryInaccessibleException;

public abstract class MemoryAccessingInstruction extends Instruction {

	public MemoryAccessingInstruction(long memoryAddress, int opcode,
			String instructionToken) {
		super(memoryAddress, opcode, instructionToken);
	}

	@Override
	protected void executeInstruction(Computer computer) {
		long aluOutput = computer.getId_ex_a().getRegisterValue() + computer.getId_ex_imm().getRegisterValue();
		computer.getEx_mem_aluOutput().setRegisterValue(aluOutput);
	}
	
	@Override
	protected void executeMemoryAccess(Computer computer) throws MemoryInaccessibleException {
		if (computer.isMemoryInUse()) {
			throw new MemoryInaccessibleException();
		}
		computer.setMemoryInUse(true);
		operateOnMemory(computer);
	}
	
	protected abstract void operateOnMemory(Computer computer);

	@Override
	protected void executeWriteBack(Computer computer) {
		computer.setMemoryInUse(false);
		operateWriteBack(computer);
	}
	
	protected abstract void operateWriteBack(Computer computer);
	
}
